
#include <config.h>
#include <input_manager.h>
#include <stdlib.h>
#include <draw.h>
#include <tslib.h>

static struct tsdev *g_ptTS;
static int g_iXres;
static int g_iYres;

static T_InputOpr g_tTouchscreenInputOpr;

static int TouchscreenDeviceInit(void)
{
	char *pcTSdevice=NULL;

	if((pcTSdevice = getenv("TSLIB_TSDEVICE")) != NULL)
	{
		g_ptTS = ts_open(pcTSdevice,0);
	}
	else
	{
		g_ptTS = ts_open("/dev/event1", 0);
	}

	if (!g_ptTS)
	{
		DBG_PRINTF("ts_open error\n");
		return -1;;
	}

	if (ts_config(g_ptTS))
	{
		DBG_PRINTF("ts_config error\n");
		return -1;
	}

	if(GetResolution(&g_iXres, &g_iYres))
	{
		DBG_PRINTF("GetResolution error\n");
		return -1;
	}
	
	return 0;
}

static int TouchscreenDeviceExit(void)
{
	return 0;
}

static int TouchscreenGetInputEvent(PT_InputEvent ptInputEvent)
{
	struct ts_sample tSampPressured;
	struct ts_sample tSampReleased;
	struct ts_sample tSamp;
	int iRet;
	int bStart = 0;
	int iDeltaX = 0;
	
	while(1)
	{
		iRet = ts_read(g_ptTS, &tSamp, 1);
		
		if (iRet == 1)
		{
			if((bStart == 0) && (tSamp.pressure > 0))
			{
				tSampPressured = tSamp;
				bStart = 1;
			}
			
			if(tSamp.pressure <= 0)
			{
				tSampReleased = tSamp;
				if(!bStart)
				{
					return -1;
				}
				else
				{
					ptInputEvent->iType = INPUT_TYPE_TOUCHSCREEN;
					ptInputEvent->tTime = tSampPressured.tv;
			
					iDeltaX = tSampReleased.x - tSampPressured.x;
					if(iDeltaX > g_iXres/10)
					{
						ptInputEvent->iVal = INPUT_VAL_UP;
					}
					else if(iDeltaX < 0 - g_iXres/10)
					{
						ptInputEvent->iVal = INPUT_VAL_DOWN;
					}
					else
					{
						ptInputEvent->iVal = INPUT_VAL_UNKNOW;
					}
					return 0;
				}
			}
		}
		else
		{
			return -1;
		}		
	}
	return 0;
}

static T_InputOpr g_tTouchscreenInputOpr = {
	.name = "touchscreen",
	.DeviceInit = TouchscreenDeviceInit,
	.DeviceExit = TouchscreenDeviceExit,
	.GetInputEvent = TouchscreenGetInputEvent,
};

int TouchscreenRegister(void)
{
	return RegisterInputOpr(&g_tTouchscreenInputOpr);
}

